#include "HttpServer.hpp"
#include <memory>

using namespace std;
using namespace server;

void Usage(std::string proc)
{
    cerr << "Usage:\n\t" << proc << " port\r\n\r\n";
}

std::string suffixToDesc(const std::string suffix)
{
    std::string ct = "Content-Type: ";
    if (suffix == ".html")
        ct += "text/html";
    else if (suffix == ".jpg")
        ct += "application/x-jpg";

    ct += "\r\n";
    return ct;
}

// 1. 服务器和网页分离，html
// 2. url -> / : web根目录
// 3. 正确给客户端返回资源类型，所有的资源都需要有后缀
bool Get(const HttpRequest &req, HttpResponse &resp)
{
    cout << "--------------------------------------http start----------------------------------------------" << endl;
    cout << req.inbuffer << endl;
    std::cout << "method: " << req.method << std::endl;
    std::cout << "url: " << req.url << std::endl;
    std::cout << "httpversion: " << req.httpversion << std::endl;
    std::cout << "path: " << req.path << std::endl;
    std::cout << "suffix: " << req.suffix << std::endl;
    std::cout << "size: " << req.size << "字节" << std::endl;
    cout << "--------------------------------------http end----------------------------------------------" << endl;

    string respline = "HTTP/1.1 200 OK\r\n";
    string respheader = suffixToDesc(req.suffix);
    if (req.size > 0)
    {
        respheader += "Content-length: ";
        respheader += std::to_string(req.size);
        string respblank = "\r\n";
    }
    string respblank = "\r\n";

    // string body = "<html lang=\"en\"><head><meta charset=\"UTF-8\"><title>for test</title><h1>hello world</h1><head><body><p>在孩子的成长旅程中，音乐就像是一位神奇的伙伴，尤其是那充满活力的音乐律动游戏，更是为孩子们的发展注入了源源不断的动力。</p></body><html>";

    string body;
    if (!Util::readFile(req.path, &body))
    {
        Util::readFile(html_404, &body);
    }
    resp.outbuffer += respline;
    resp.outbuffer += respheader;
    resp.outbuffer += respblank;
    resp.outbuffer += body;

    return true;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    uint16_t port = atoi(argv[1]);
    unique_ptr<HttpServer> httpsvr(new HttpServer(Get, port));
    
    httpsvr->registerCb("/",Get);
    httpsvr->initServer();
    httpsvr->start();

    return 0;
}